// pages/detail-search/index.js
import { getSearchHot, getSearchSuggest, getSearchResult } from "../../server/api_seach"
import debounce from "../../utils/debounce"
import { stringToNode } from "../../utils/string2nodes"

const debounceGetSearchSuggest = debounce(getSearchSuggest, 200)

Page({
    data: {
        horKeywords: [],
        suggestSongs: [],
        suggestSongsNodes: [],
        resultSongs: [],
        searchValue: ""
    },
    onLoad: function (options) {
        // 获取页面数据
      this.getPageData()
    },
// 事件处理
handleSearchChange: function(event) {
    const searchValue = event.detail
    this.setData({ searchValue })
    if(!searchValue.length) {
        this.setData({ 
            suggestSongs: [], 
            resultSongs: []
         })
        debounceGetSearchSuggest.cancel()
        return
    }
        // 根据关键字进行搜索
debounceGetSearchSuggest(searchValue).then(res => {
            // 1.获取建议的关键字
            const suggestSongs = res.result.allMatch
            this.setData({ suggestSongs })
            if(!suggestSongs) return

            // 2.转成nodes节点
            const suggestKeywords = suggestSongs.map(item => item.keyword)
            const suggestSongsNodes = []
            for(const keyword of suggestKeywords) {
                const nodes = stringToNode(keyword, searchValue)
                suggestSongsNodes.push(nodes)
            }
            this.setData({ suggestSongsNodes })
    })
},
    
getPageData: function() {
    getSearchHot().then(res => {
        this.setData({horKeywords: res.result.hots})
    })
 },
 handleSearchAction: function() {
     const serachValue = this.data.searchValue
     getSearchResult(serachValue).then(res => {
         this.setData({resultSongs: res.result.songs})
     })
 },
 handlekeywordItemClick(event) {
     const keyword = event.currentTarget.dataset.keyword
    //  2将关键字设置到searchValue中
    this.setData({ searchValue: keyword})
    // 3发送网咯请求
    this.handleSearchAction()
 },


})